package 链表.单向.练习;

import org.omg.PortableInterceptor.LOCATION_FORWARD;

//找出倒数第k个数
public class Text_3 {
    public static ListNode head;
    public void addFirst(int data){
        //代码不能交换
        //必须先绑定信息
        ListNode listNode = new ListNode(data);
        listNode.next = head;
        head = listNode;
    }
    void display(){
        ListNode cur = head;
        while (cur!=null){
            System.out.print(cur.val+" ");
            cur = cur.next;//cur向后走一步
        }
        System.out.println();
    }
    int  size(){
        int count = 0;
        ListNode cur = head;
        while (cur!=null){
            cur = cur.next;
            count++;
        }
        return count;
    }
    ListNode findListNode(int k){
        //快的比慢的先走了k-1个，那么快的到了，满的就是倒数第k个
        if(head ==null){
            return null;
        }
        if(k<=0||k>size()){
            System.out.println("k取值不对");
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        int count = k-1;

        while (count>0){
            fast = fast.next;
            count--;
        }
        while(fast!=null&&fast.next!=null){
            fast =fast.next;
            slow =slow.next;
        }
        return slow;
    }

    public static void main(String[] args) {
        Text_3 text3 = new Text_3();
        text3.addFirst(3);
        text3.addFirst(2);
        text3.addFirst(1);
        text3.display();
        ListNode x = text3.findListNode(2);
        System.out.println(x.val);

    }
}
